package com.cxyd.modules.job.task.wmsTask;

import com.cxyd.common.utils.ApiResult;
import com.cxyd.modules.wcs.dto.PostWmsDTO;
import com.cxyd.modules.wcs.entity.UrlMappingEntity;
import com.cxyd.modules.wcs.service.PostWmsService;
import com.cxyd.modules.wcs.service.UrlMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component("post-wms")
@Slf4j
public class PostWmsTask {
    @Resource
    private PostWmsService postWmsService;
    @Resource
    private UrlMappingService urlService;
    @Resource
    private RestTemplate restTemplate;
    //创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    public void scanPost() {
        lock.lock();
        try {
//            优先获取一下路由信息
            UrlMappingEntity url_wms = urlService.getUrlByNo("WMS_POST_URL");
            if (url_wms == null || url_wms.getUrlAdr().isEmpty()) {
                log.info("[WMS_POST_URL]未配置!");
                return;
            }
            final PostWmsDTO record = postWmsService.getPostWms();
            if (record == null) {
//                log.info("[wcs_post_wms]中没有需要下发的数据.");
                return;
            }
            log.info("获取到待上报指令：{}", record);
            ApiResult respond = restTemplate.postForObject(url_wms.getUrlAdr(), record, ApiResult.class);
            if (respond == null) {
                log.error("上位系统无响应!");
                return;
            }
            /*发送成功则处理数据*/
            if (respond.getRequestPk().isEmpty()) {
                return;
            }
            log.info("获取WMS反馈:code:{},msg:{},requestPk:{}", respond.getCode(), respond.getMsg(), respond.getRequestPk());
            postWmsService.postWmsHandle(record, respond);
        } catch (Exception e) {
            log.error("[wcs_post_wms]指令上报异常，causeBy:{}", e.getMessage());
        } finally {
            lock.unlock();//释放锁
        }
    }
}
